/**
 * Created by CK on 2017/6/23.
 */

/**
 * dataGrid 事件
 *
 * @param _dom
 * @param _url
 * @param _params
 *
 * create by ck 20170623
 */
function xhDataGrid(_dom, _url, _params){
    this.isInit         = false;
    this.list           = _dom;
    this.url            = baseUrl + _url;
    this.params         = _params || {};
    this.title          = null;
    this.onLoadSuccess  = function(data){
        xhExtra.checkError(data);
    };
    this.onClickRow     = function(rowIndex, rowData){};        //单击行事件
    this.onDblClickRow  = function(rowIndex, rowData){};        //双击行事件
    this.onSelect       = function(rowIndex, rowData){};        //选中事件
    this.onUnselect     = function(rowIndex, rowData){};        //取消选中事件
    this.onSelectAll    = function(rows){};                     //全选事件
    this.onUnselectAll  = function(rows){};                     //取消全选事件
    this.onCheck        = function(rowIndex, rowData){};        //勾选事件
    this.onUncheck      = function(rowIndex, rowData){};        //取消勾选事件
    this.onCheckAll     = function(rows){};                     //全部勾选事件
    this.onUncheckAll   = function(rows){};                     //取消全部勾选事件
    this.onUncheckAll   = function(rows){};                     //取消全部勾选事件
    this.rowStyler      = function(rowIndex, rowData){};        //行样式
    this.onDblClickCell = function(rowIndex, field, value){};   //双击单元格
    this.onSortColumn   = function(sort, order){};
    this.onLoadError    = function(){
        window.top.xhTop.showError('数据加载失败！');
    };
    this.loadFilter     = function(data) {
        return data;
    };

    /**
     * 初始化表单
     *
     * @returns {xhDataGrid}
     *
     * create by ck 20170627
     */
    this.init = function(_url, _params){
        var $this = this;
        $this.list.datagrid({
            url: _url || $this.url,
            queryParams: _params || $this.params,
            onLoadSuccess: function(data){
                $this.onLoadSuccess(data);
            },
            onLoadError: function(){
                $this.onLoadError();
            },
            onClickRow: function(rowIndex, rowData){
                $this.onClickRow(rowIndex, rowData);
            },
            onDblClickRow: function(rowIndex, rowData){
                $this.onDblClickRow(rowIndex, rowData);
            },
            onSelect: function(rowIndex, rowData){
                $this.onSelect(rowIndex, rowData);
            },
            onUnselect: function(rowIndex, rowData){
                $this.onUnselect(rowIndex, rowData);
            },
            onSelectAll: function(rows){
                $this.onSelectAll(rows);
            },
            onUnselectAll: function(rows){
                $this.onUnselectAll(rows);
            },
            onCheck: function(rowIndex, rowData){
                $this.onCheck(rowIndex, rowData);
            },
            onUncheck: function(rowIndex, rowData){
                $this.onUncheck(rowIndex, rowData);
            },
            onCheckAll: function(rows){
                $this.onCheckAll(rows);
            },
            onUncheckAll: function(rows){
                $this.onUncheckAll(rows);
            },
            rowStyler: function(rowIndex, rowData){
                return $this.rowStyler(rowIndex, rowData);
            },
            onDblClickCell: function(rowIndex, field, value) {
                $this.onDblClickCell(rowIndex, field, value);
            },
            onSortColumn: function(sort, order){
                $this.onSortColumn(sort, order);
            },
            loadFilter: function(data) {
                return $this.loadFilter(data);
            }
        });
        $this.isInit = true;
        $this.title  = $this.list.datagrid('getPanel').panel('options').title;
        return $this;
    };
    /**
     * 刷新表单
     *
     * @param _params
     * @returns {xhDataGrid}
     *
     * create by ck 20170627
     * modify by ck 20170705    添加参数，可传入额外参数（用于搜索）
     * modify by ck 20170715    判断是否已经初始化，否则先初始化
     */
    this.reload = function(_params){
        var $this = this;
        if(!$this.isInit){
            $this.init(null, _params);
            $this.isInit = true;
        }
        else {
            if (!_params) {
                window.setTimeout(function () {
                    $this.list.datagrid('reload');
                }, 100);
            }
            else {
                _params = $.extend({}, $this.params, _params);
                $this.list.datagrid('load', _params)
            }
            $this.list.datagrid('clearSelections');
        }
        return $this;
    };
    /**
     * 清除选中信息
     *
     * @returns {xhDataGrid}
     *
     * create by ck 2010701
     */
    this.clear = function(){
        this.list.datagrid('clearSelections');
        return this;
    };
    /**
     * 设置按钮联动
     *
     * @returns {xhDataGrid}
     *
     * create by ck 20170627
     */
    this.activeButton = function(_anyArr, _oneArr, _type) {
        var $this = this;
        if (!_anyArr) _anyArr = [];
        if (!_oneArr) _oneArr = [];
        if (!_type)   _type   = 'eu';
        $.each(_anyArr, function (_name, _value) {
            xhExtra.disableButton($('#' + _value), _type);
        });
        $.each(_oneArr, function (_name, _value) {
            xhExtra.disableButton($('#' + _value), _type);
        });
        $this.onSelect = function () {
            $.each(_anyArr, function (_name, _value) {
                xhExtra.enableButton($('#' + _value), _type);
            });
            if ($this.list.datagrid('getSelections').length == 1) {
                $.each(_oneArr, function (_name, _value) {
                    xhExtra.enableButton($('#' + _value), _type);
                });
            } else {
                $.each(_oneArr, function (_name, _value) {
                    xhExtra.disableButton($('#' + _value), _type);
                });
            }
        };
        $this.onUnselect = function () {
            var _length = $this.list.datagrid('getSelections').length;
            if (_length == 0) {
                $.each(_anyArr, function (_name, _value) {
                    xhExtra.disableButton($('#' + _value), _type);
                });
            }
            if (_length == 1) {
                $.each(_oneArr, function (_name, _value) {
                    xhExtra.enableButton($('#' + _value), _type);
                });
            }
            else {
                $.each(_oneArr, function (_name, _value) {
                    xhExtra.disableButton($('#' + _value), _type);
                });
            }
        };
        $this.onSelectAll = function () {
            $.each(_anyArr, function (_name, _value) {
                xhExtra.enableButton($('#' + _value), _type);
            });
            if ($this.list.datagrid('getSelections').length == 1) {
                $.each(_oneArr, function (_name, _value) {
                    xhExtra.enableButton($('#' + _value), _type);
                });
            }
            else {
                $.each(_oneArr, function (_name, _value) {
                    xhExtra.disableButton($('#' + _value), _type);
                });
            }
        };
        $this.onUnselectAll = function () {
            $.each(_anyArr, function (_name, _value) {
                xhExtra.disableButton($('#' + _value), _type);
            });
            if ($this.list.datagrid('getSelections').length == 1) {
                $.each(_oneArr, function (_name, _value) {
                    xhExtra.enableButton($('#' + _value), _type);
                });
            }
            else {
                $.each(_oneArr, function (_name, _value) {
                    xhExtra.disableButton($('#' + _value), _type);
                });
            }
        };
        return $this;
    };
    /**
     * 设置按钮联动 --新，直接传入对象
     *
     * @param _anyArr
     * @param _oneArr
     * @param _type
     * @returns {xhDataGrid}
     *
     * create by ck 20171214
     */
    this.activeBtn = function(_anyArr, _oneArr, _type) {
        var $this = this;
        if (!_anyArr) {
            _anyArr = $();
        }
        if (!_oneArr) {
            _oneArr = $();
        }
        if (!_type) {
            _type = 'eu';
        }
        xhExtra.disableButton(_anyArr.add(_oneArr), _type);
        $this.onSelect = function () {
            xhExtra.enableButton(_anyArr, _type);
            if ($this.command('getSelections').length === 1) {
                xhExtra.enableButton(_oneArr, _type);
            } else {
                xhExtra.disableButton(_oneArr, _type);
            }
        };
        $this.onUnselect = function () {
            var _length = $this.command('getSelections').length;
            if (_length === 0) {
                xhExtra.disableButton(_anyArr, _type);
            }
            if (_length === 1) {
                xhExtra.enableButton(_oneArr, _type);
            }
            else {
                xhExtra.disableButton(_oneArr, _type);
            }
        };
        $this.onSelectAll = function () {
            xhExtra.enableButton(_anyArr, _type);
            if ($this.command('getSelections').length === 1) {
                xhExtra.enableButton(_oneArr, _type);
            }
            else {
                xhExtra.disableButton(_oneArr, _type);
            }
        };
        $this.onUnselectAll = function () {
            xhExtra.disableButton(_anyArr.add(_oneArr), _type);
        };
        return $this;
    };
    /**
     * 渲染表格工具栏，有回调则完成后调用回调函数
     *
     * @param _callback
     * @returns {xhDataGrid}
     *
     * create by ck 20170701
     */
    this.parseToolbar = function(_callback){
        if(_callback) {
            $.parser.onComplete = function(){ _callback.call(this); };
        }
        var listToolbar = $('#' + this.list[0].id + '_toolbar');
        listToolbar.find('input[type=text]').each(function(){
            $(this).addClass('easyui-textbox');
        });
        listToolbar.find('select').each(function(){
            $(this).addClass('easyui-combobox');
            $(this).attr('editable','false');
            if($(this).children().length <= 8){
                $(this).attr('panelHeight','auto');
            }
        });
        listToolbar.find('a').each(function(){
            if($(this).attr('class')) return true;
            $(this).addClass('easyui-linkbutton');
        });
        $.parser.parse(listToolbar);
        return this;
    };

    /**
     * 获取选中行指定值
     *
     * @param _field
     * @returns {*}
     *
     * create by ck 20170627
     * modify by ck 20170809    _field为true则返回整行
     */
    this.getSelectValue = function(_field){
        var _row = this.list.datagrid('getSelected');
        return _row ? (_field === true ? _row : eval('_row.'+_field)) : null;
    };
    /**
     * 获取选中行指定值（多个）
     *
     * @param _fields
     * @returns {*}
     *
     * create by ck 20170627
     * modify by ck 20170722    过滤空数据
     * modify by ck 20170817    可传入数组获取多个值
     */
    this.getSelectValues = function(_fields){
        var _rows   = this.list.datagrid('getSelections'),
            _values = [],
            _tmp    = '';
            // _tmp    = typeof _fields === 'object' ? {} : '';
        for(var i=0; i<_rows.length; i++){
            // if (typeof _fields === 'string'){
            //     _tmp = eval('_rows['+i+'].'+_fields);
            // }
            // else if (typeof _fields === 'object'){
            //     $.each(_fields, function (index, _field) {
            //         _tmp[_field] = eval('_rows['+i+'].'+_field);
            //     });
            // }
            _tmp = eval('_rows['+i+'].'+_fields);
            // if(_tmp){
                _values.push(_tmp);
            // }
        }
        return _values;
    };
    /**
     * 合并单元格
     *
     * @param _colArr
     * @returns {*}
     *
     * create by ck 20170627
     */
    this.mergeCells = function(_colArr) {
        var $this   = this,
            TableRowCnts = $this.list.datagrid('getRows').length,
            tmpA, tmpB, PerTxt = "", CurTxt = "";
        for (var j = _colArr.length - 1; j >= 0; j--) {
            PerTxt = "";
            tmpA = 1;
            tmpB = 0;

            for (var i = 0; i <= TableRowCnts; i++) {
                if (i == TableRowCnts) {
                    CurTxt = "";
                }
                else {
                    CurTxt = $this.list.datagrid('getRows')[i][_colArr[j]];
                }
                if (PerTxt == CurTxt) {
                    tmpA += 1;
                }
                else {
                    tmpB += tmpA;
                    $this.list.datagrid('mergeCells', {
                        index: i - tmpA,
                        field: _colArr[j],　　//合并字段
                        rowspan: tmpA,
                        colspan: null
                    });
                    $this.list.datagrid('mergeCells', { //根据_colArr[j]进行合并
                        index: i - tmpA,
                        field: 'Ideparture',
                        rowspan: tmpA,
                        colspan: null
                    });

                    tmpA = 1;
                }
                PerTxt = CurTxt;
            }
        }
        return $this;
    };
    /**
     * 监听勾选事件，并回调函数
     *
     * @param _callback
     * @returns {xhDataGrid}
     *
     * create by ck 20171129
     */
    this.onChangeCheck = function (_callback) {
        this.onCheck = function (rowIndex, rowData) {
            _callback.call(this);
        };
        this.onUncheck = function (rowIndex, rowData) {
            _callback.call(this);
        };
        this.onCheckAll = function (rows) {
            _callback.call(this);
        };
        this.onUncheckAll = function (rows) {
            _callback.call(this);
        };
        return this;
    };
    /**
     * 执行命令
     *
     * @returns {*}
     *
     * create by ck 20171130
     */
    this.command = function (command, argv1, argv2) {
        return this.list.datagrid(command, argv1, argv2);
    };
    /**
     * 设置标题，可叠加
     *
     * @param title
     * @param appendTitle
     *
     * create by ck 20171203
     */
    this.setTitle = function (title, appendTitle) {
        this.list.datagrid('getPanel').panel('setTitle', (title || this.title) + (appendTitle || ''));
        return this;
    }
}